package com.smedi.ismedi.notification.core.domain.service.impl;

import com.smedi.ismedi.notification.core.domain.aggregatemodel.SmsTemplate;
import com.smedi.ismedi.notification.core.domain.repository.SmsTemplateRepository;
import com.smedi.ismedi.notification.core.domain.service.SmsTemplateDomainService;
import com.smedi.ismedi.notification.core.infrastructure.constant.ConstantField;
import com.smedi.ismedi.notification.core.infrastructure.constant.CustomError;
import com.smedi.ismedi.notification.core.infrastructure.enumerate.SmsTemplateStatusEnum;
import com.smedi.ismedi.web.starter.exception.LogicException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @Author: xulinjun
 * @Date: 2021-7-1 21:14
 */
@Slf4j
@Service
@AllArgsConstructor
public class SmsTemplateDomainServiceImpl implements SmsTemplateDomainService {
    private final SmsTemplateRepository smsTemplateRepository;

    /**
     * 校验文本是否为数字
     *
     * @param str
     * @return
     */
    private boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    /**
     * 获取参数个数
     *
     * @param content
     * @return
     */
    private int getTemplateParameters(String content) {
        String words = content;
        int i = 0;
        while (words.contains("{")) {
            words = words.substring(words.indexOf("{") + 1);
            String text = words.substring(0, words.indexOf("}"));
            boolean error = false;
            if (isNumeric(text)) {
                int a = Integer.valueOf(text);
                if (a <= 0) {
                    error = false;
                }
                if (a != i) {
                    error = false;
                }
            } else {
                error = false;
            }
            if (error) throw LogicException.raise(CustomError.TEMPLATE_PARAMETER_ERROR);
            i++;
        }
        return i;
    }

    @Override
    public SmsTemplate createTemplate(SmsTemplate smsTemplate) {
        // 判断字数，如果字数超过最大字数显示报错
        if (smsTemplate.getTemplateContent().length() > ConstantField.messageContentLength) {
            throw LogicException.raise(CustomError.MESSAGE_CONTENT_LENGTH_ERROR);
        }

        // 保存至后台数据
        smsTemplate.setParameters(getTemplateParameters(smsTemplate.getTemplateContent())) // 拆分参数链接，将参数定位出来，也为未来拼接参数方便
                .setStatus(SmsTemplateStatusEnum.IN_APPROVAL.getValue()) // 默认审批中
                .setAvailable(false);

        return smsTemplateRepository.doInsert(smsTemplate);
    }

    @Override
    public SmsTemplate setTencentTemplateId(SmsTemplate smsTemplate) {
        SmsTemplate basic = smsTemplateRepository.selectBySmsTemplateId(smsTemplate.getSmsTemplateId());
        if (basic == null) {
            throw LogicException.raise(CustomError.TEMPLATE_NOT_FOUND);
        } else {
            basic.setTencentTemplateId(smsTemplate.getTencentTemplateId());
            return smsTemplateRepository.doUpdate(basic);
        }
    }

    @Override
    public SmsTemplate updateTemplate(SmsTemplate smsTemplate) {
        SmsTemplate basic;
        if (smsTemplate.getSmsTemplateId() != null) {
            basic = smsTemplateRepository.selectBySmsTemplateId(smsTemplate.getSmsTemplateId());
            if (basic == null) {
                throw LogicException.raise(CustomError.TEMPLATE_NOT_FOUND);
            }
        } else {
            throw LogicException.raise(CustomError.SMS_TEMPLATE_ID_MISS);
        }

        // 腾讯模板id不允许请求传入
        basic.setStatus(SmsTemplateStatusEnum.IN_APPROVAL.getValue())
                .setParameters(getTemplateParameters(smsTemplate.getTemplateContent()))
                .setRemark(smsTemplate.getRemark())
                .setTemplateContent(smsTemplate.getTemplateContent())
                .setTemplateName(smsTemplate.getTemplateName())
                .setAvailable(false);

        return smsTemplateRepository.doUpdate(basic);
    }

    @Override
    public SmsTemplate queryTemplateBySmsTemplateId(Long smsTemplateId) {
        return smsTemplateRepository.selectBySmsTemplateId(smsTemplateId);
    }

    @Override
    public Boolean validateTemplate(Long smsTemplateId) {
        SmsTemplate smsTemplate = smsTemplateRepository.selectBySmsTemplateId(smsTemplateId);
        if (smsTemplate != null) {
            // 判断当前模板是否可以使用
            return smsTemplate.isAvailable();
        } else {
            return false;
        }
    }

    @Override
    public Long deleteTemplate(Long smsTemplateId) {
        SmsTemplate smsTemplate = queryTemplateBySmsTemplateId(smsTemplateId);
        if (smsTemplate.getTencentTemplateId() != null) {
            smsTemplateRepository.doDelete(smsTemplateId);
            return smsTemplate.getTencentTemplateId();
        } else {
            throw LogicException.raise(CustomError.TENCENT_TEMPLATE_ID_NOT_BOUND);
        }
    }

    @Override
    public SmsTemplate updateTemplateStatus(Long smsTemplateId, Long status) {
        SmsTemplate smsTemplate = queryTemplateBySmsTemplateId(smsTemplateId);

        if (status == 1L) {
            smsTemplate.setStatus(SmsTemplateStatusEnum.IN_APPROVAL.getValue())
                    .setAvailable(false);
        } else if (status == 0L) {
            smsTemplate.setStatus(SmsTemplateStatusEnum.APPROVED.getValue())
                    .setAvailable(true);
        } else {
            smsTemplate.setStatus(SmsTemplateStatusEnum.REJECTED.getValue())
                    .setAvailable(false);
        }

        return smsTemplateRepository.doUpdate(smsTemplate);
    }

    @Override
    public List<SmsTemplate> findListBySmsTemplateStatus(String smsTemplateStatus) {
        return smsTemplateRepository.selectBySmsTemplateStatus(smsTemplateStatus);
    }

    @Override
    public SmsTemplate queryTemplateBySmsTemplateName(String smsTemplateName) {
        return smsTemplateRepository.selectBySmsTemplateName(smsTemplateName);
    }
}
